package maven;

import E10.ebrestful.Add;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import db.ConnectionHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {


    /**
     * 前缀
     */
    private static final String preFix = "[INFO] ";
    private static String token_a ="";
    public static void main(String[] args) throws SQLException {
        Main main = new Main();
        boolean allJarName = main.getAllJarForProjectList(Arrays.asList("ai", "core"));
        System.out.println("allJarName = " + allJarName);
    }

    public boolean getAllJarForProjectList(List<String> nameList) {
        List<TreeNode> allChildren = new ArrayList<>();
        for (String name : nameList) {
            TreeNode treeNode = getTreeNode(name);
            allChildren.addAll(treeNode.getAllChildren());
        }
        List<String> allJarName = allChildren.stream().map(TreeNode::getJarName).distinct().collect(Collectors.toList());
        String collect = nameList.stream().collect(Collectors.joining("_"));
        FileWriter fileWriter = new FileWriter("C:\\Datas\\maven\\"+collect);
        for (String jarName : allJarName) {
            fileWriter.write(jarName+"\n",true);
        }
        return true;
    }


    private static TreeNode getTreeNode(String projectName) {
        TreeNode rootNode;
        FileReader fr;
        List<String> strings;
        fr = new FileReader("C:\\Users\\LENOVO\\AppData\\Roaming\\JetBrains\\IntelliJIdea2022.3\\scratches\\dangan\\"+projectName);

        strings = fr.readLines();
        rootNode = new TreeNode();
        for (String string : strings) {
            handleNode(string,rootNode);
        }
        return rootNode;
    }

    private static void addTree2(List<TreeNode> allChildren) throws SQLException {
        Map<Long, TreeNode> allTreenodeMap = allChildren.stream().collect(Collectors.toMap(TreeNode::getId, e -> e));
        int batchSize = 100;
        // 使用 IntStream.rangeClosed() 创建一个索引范围，并进行批处理
        List<List<TreeNode>> batches = IntStream.rangeClosed(0, (allChildren.size() - 1) / batchSize)
                .mapToObj(i -> allChildren.subList(i * batchSize, Math.min((i + 1) * batchSize, allChildren.size())))
                .collect(Collectors.toList());
        for (List<TreeNode> batch : batches) {
            JSONArray datas = new JSONArray();
            for (TreeNode treeNode : batch) {
                JSONObject mainTable = new JSONObject();
                mainTable.put("ssgc",treeNode.getProjectName());
                mainTable.put("scope",treeNode.getScope());
                mainTable.put("jar",treeNode.getJarName());

                String allJarName = treeNode.getParentId() == null? treeNode.getJarName():getAllJarName(treeNode.getJarName(), allTreenodeMap, treeNode.getParentId());
                mainTable.put("jarmc", allJarName);
                mainTable.put("sjkey", treeNode.getParentId());
                mainTable.put("bjdkey", treeNode.getId());
                mainTable.put("sfzjyl",treeNode.getDependencyMode()==DependencyMode.direct?1:0);
                JSONObject data = new JSONObject();
                data.put("mainTable",mainTable);
                PreparedStatement preparedStatement = testConnection.prepareStatement("select 1 from uf_shxl_maven where jarmc = ? and (delete_type = 0 or delete_type is null)");
                preparedStatement.setString(1,allJarName);
                ResultSet resultSet = preparedStatement.executeQuery();
                if (resultSet.next()) {
                    return;
                }
                datas.add(data);
            }
            Add.addData(datas,token_a,"e7b1a3");
        }
    }

    public static String getAllJarName(String allJarName, Map<Long,TreeNode> allTreeNode,Long parentId) {
        TreeNode treeNode = allTreeNode.get(parentId);
        allJarName =treeNode.getJarName()+"@@"+ allJarName;
        if (treeNode.getParentId() != null) {
            allJarName = getAllJarName(allJarName,allTreeNode,treeNode.getParentId());
        }
        return allJarName;
    }

    private static void addTree(List<TreeNode> treeNodes, Long parentId,String allJarName) throws SQLException {
        for (TreeNode treeNode : treeNodes) {
            JSONArray datas = new JSONArray();
            JSONObject mainTable = new JSONObject();
            mainTable.put("ssgc",treeNode.getProjectName());
            mainTable.put("scope",treeNode.getScope());
            mainTable.put("jar",treeNode.getJarName());
            mainTable.put("bjdkey",treeNode.getId());
            mainTable.put("sjkey",treeNode.getParentId());
            if (treeNode.getParentId() == null) {
                allJarName = treeNode.getJarName();
            } else {
                allJarName +=("@@"+treeNode.getJarName());
            }
            mainTable.put("jarmc", allJarName);
            mainTable.put("sfzjyl",treeNode.getDependencyMode()==DependencyMode.direct?1:0);
            if (parentId != null) {
                mainTable.put("sj",parentId);
            }
            JSONObject data = new JSONObject();
            data.put("mainTable",mainTable);
            datas.add(data);
            PreparedStatement preparedStatement = testConnection.prepareStatement("select 1 from uf_shxl_maven where jarmc = ? and (delete_type = 0 or delete_type is null)");
            preparedStatement.setString(1,allJarName);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                return;
            }
            boolean isok = false;
            Long aLong = -1L;
            while (!isok) {
                String s = "";
                try {
                    s = Add.addData(datas, token_a, "e7b1a3");
                    System.out.println("s = " + s);
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    JSONObject datajson = jsonObject.getJSONObject("datajson");
                    JSONArray result = datajson.getJSONArray("dataIds");
                    aLong = result.getLong(0);
                    isok = true;
                } catch (Exception e) {
                    System.out.println(s);
                }

            }
            List<TreeNode> childTreeNodes = treeNode.getTreeNodes();
            if (childTreeNodes != null) {
                addTree(childTreeNodes,aLong,allJarName);

            }
        }
    }
    private static Connection testConnection = ConnectionHelper.getTestConnection();

    private static void addJar(List<TreeNode> allChildren, String token) throws SQLException {
        int batchSize = 100;
        Set<String> collect = allChildren.stream().map(TreeNode::getJarName).collect(Collectors.toSet());
        ArrayList<String> jarnames = new ArrayList<>(collect);
        // 使用 IntStream.rangeClosed() 创建一个索引范围，并进行批处理
        List<List<String>> batches = IntStream.rangeClosed(0, (jarnames.size() - 1) / batchSize)
                .mapToObj(i -> jarnames.subList(i * batchSize, Math.min((i + 1) * batchSize, jarnames.size())))
                .collect(Collectors.toList());
        for (List<String> treeNodes : batches) {
            JSONArray datas = new JSONArray();
            for (String treeNode : treeNodes) {
                JSONObject mainTable = new JSONObject();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("jarmc",treeNode);
                mainTable.put("mainTable",jsonObject);
                PreparedStatement preparedStatement = testConnection.prepareStatement("select 1 from uf_shxl_jar where jarmc = '"+treeNode+"'  and (delete_type = 0 or delete_type is null)" );
                ResultSet resultSet = preparedStatement.executeQuery();
                if (!resultSet.next()) {
                    datas.add(mainTable);
                }
            }
            if (datas.size() > 0) {
                Add.addData(datas, token,"f1b697");
            }
        }
    }


    private static Map<Integer,TreeNode> levelNodeMap = new HashMap<>();

    private static long id;
    private static String  projectName;


    public static void handleNode(String currentInfo, TreeNode node) {
        String[] infos = currentInfo.substring(preFix.length()).split(":jar:");
        currentInfo = infos[0];
        String info = infos[1];
        Scope scope = getScope(info);
        int directIndex = currentInfo.indexOf("+-");
        DependencyMode dependencyMode = DependencyMode.direct;
        if (directIndex == -1) {
            directIndex = currentInfo.indexOf("\\-");
            dependencyMode = DependencyMode.indirect;
        }
        if (directIndex == -1) {
            projectName = currentInfo;
            return;
        }
        int level = directIndex/3;
        TreeNode currentNode = new TreeNode();
        if (scope == null) {
            throw new RuntimeException("scope解析异常");
        }
        currentNode.setScope(scope);
        currentNode.setDependencyMode(dependencyMode);
        //得到jar包信息，没有jar包后缀有引用方式的
        if (currentInfo.startsWith(DependencyMode.indirect.getDependencyFlag())) {
            currentNode.setDependencyMode(DependencyMode.indirect);
        }
        if (currentInfo.startsWith(DependencyMode.direct.getDependencyFlag())) {
            currentNode.setDependencyMode(DependencyMode.direct);
        }
        currentNode.setProjectName(projectName);
        currentInfo = currentInfo.substring((level+1) * 3);
        currentNode.setJarName(currentInfo);
        currentNode.setId(getId());


        if (level > 0) {
            TreeNode parentNode = levelNodeMap.get(level - 1);
            currentNode.setParentId(parentNode.getId());
            List<TreeNode> treeNodes = Optional.ofNullable(parentNode.getTreeNodes()).orElse(new ArrayList<>());
            treeNodes.add(currentNode);
            parentNode.setTreeNodes(treeNodes);
        } else {
            List<TreeNode> treeNodes = Optional.ofNullable(node.getTreeNodes()).orElse(new ArrayList<>());
            treeNodes.add(currentNode);
            node.setTreeNodes(treeNodes);
        }
        levelNodeMap.put(level,currentNode);

    }

    private static Scope getScope(String info) {
        for (Scope value : Scope.values()) {
            if (info.endsWith(value.name())) {
                return value;
            }
        }
        return null;
    }

    private static long getId() {
        return ++id;
    }
}
